package com.ls.lsbase.utils;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.ls.lsbase.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * 支付utils
 * Created by 林少 on 2016/12/2.
 */

public class PayUtils {
    private static final int SDK_PAY_FLAG = 1;
    private static AlipayNotify alipayNotify;
    private static Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    AlipayPayResult payResult = new AlipayPayResult((Map<String, String>) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        alipayNotify.success();
                    } else {
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            alipayNotify.loadinging();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            alipayNotify.failure();
                        }
                    }
                    break;
                }
//                case SDK_CHECK_FLAG: {
//                    ToastUtil.showShort(PayMentsAty.this, "检查结果为：" + msg.obj);
//                    break;
//                }
                default:
                    break;
            }
        }
    };

    public static void alipayPay(final Activity aty, final String orderInfo, AlipayNotify notify) {
        alipayNotify = notify;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(aty);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public interface AlipayNotify {
        void success();

        void loadinging();

        void failure();
    }

    /**
     * <activity
     * android:name="com.alipay.sdk.app.H5PayActivity"
     * android:configChanges="orientation|keyboardHidden|navigation"
     * android:exported="false"
     * android:screenOrientation="behind"
     * android:windowSoftInputMode="adjustResize|stateHidden"/>
     */

    public static void wxPayMethod(Context context, WxInfoBean wxResultBean, WxPayNotify wxPayNotify) {
        IWXAPI api = WXAPIFactory.createWXAPI(context, wxResultBean.getAppid());
        WXPayEntryActivity.api = api;
        WXPayEntryActivity.notify = wxPayNotify;
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (isPaySupported) {
            PayReq req = new PayReq();
            req.appId = wxResultBean.getAppid();
            req.partnerId = wxResultBean.getPartnerid();
            req.prepayId = wxResultBean.getPrepayid();
            req.nonceStr = wxResultBean.getNoncestr();
            req.timeStamp = wxResultBean.getTimestamp();
            req.packageValue = wxResultBean.getPackageValue();
            req.sign = wxResultBean.getSign();
            api.sendReq(req);
        } else {
            ToastUtil.showShort(context, "您未安装微信或者安装的版本过低，不支持微信支付");
        }
    }

    private static class AlipayPayResult {
        private String resultStatus;
        private String result;
        private String memo;

        public AlipayPayResult(Map<String, String> rawResult) {
            if (rawResult == null) {
                return;
            }

            for (String key : rawResult.keySet()) {
                if (TextUtils.equals(key, "resultStatus")) {
                    resultStatus = rawResult.get(key);
                } else if (TextUtils.equals(key, "result")) {
                    result = rawResult.get(key);
                } else if (TextUtils.equals(key, "memo")) {
                    memo = rawResult.get(key);
                }
            }
        }

        @Override
        public String toString() {
            return "resultStatus={" + resultStatus + "};memo={" + memo
                    + "};result={" + result + "}";
        }

        /**
         * @return the resultStatus
         */
        public String getResultStatus() {
            return resultStatus;
        }

        /**
         * @return the memo
         */
        public String getMemo() {
            return memo;
        }

        /**
         * @return the result
         */
        public String getResult() {
            return result;
        }
    }

    public class WxInfoBean {
        private String timestamp;
        private String sign;
        private String partnerid;
        private String noncestr;
        private String prepayid;
        private String packageValue;
        private String appid;

        public String getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(String timestamp) {
            this.timestamp = timestamp;
        }

        public String getSign() {
            return sign;
        }

        public void setSign(String sign) {
            this.sign = sign;
        }

        public String getPartnerid() {
            return partnerid;
        }

        public void setPartnerid(String partnerid) {
            this.partnerid = partnerid;
        }

        public String getNoncestr() {
            return noncestr;
        }

        public void setNoncestr(String noncestr) {
            this.noncestr = noncestr;
        }

        public String getPrepayid() {
            return prepayid;
        }

        public void setPrepayid(String prepayid) {
            this.prepayid = prepayid;
        }

        public String getPackageValue() {
            return packageValue;
        }

        public void setPackageValue(String packageValue) {
            this.packageValue = packageValue;
        }

        public String getAppid() {
            return appid;
        }

        public void setAppid(String appid) {
            this.appid = appid;
        }
    }

    public interface WxPayNotify {
        void success();

        void failure();
    }
    /**
     * <activity
     android:name=".wxapi.WXPayEntryActivity"
     android:exported="true"
     android:launchMode="singleTop"
     android:theme="@android:style/Theme.Translucent"/>
     */
}
